package com.student.score.main;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.student.score.entity.Student;
import com.student.score.entity.Course;
import com.student.score.entity.Score;
import com.student.score.system.ScoreSystem;

public class Main {
    private static List<Student> students = new ArrayList<>();
    private static List<Course> courses = new ArrayList<>();
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        while (true) {
            // 显示菜单
            System.out.println("\n===== 学生成绩管理系统 =====");
            System.out.println("1. 添加课程");
            System.out.println("2. 添加学生");
            System.out.println("3. 为学生添加成绩");
            System.out.println("4. 计算学生GPA");
            System.out.println("5. 查询学生课程成绩");
            System.out.println("6. 保存数据到文件");
            System.out.println("7. 从文件加载数据");
            System.out.println("0. 退出系统");
            System.out.print("请选择操作：");

            // 处理输入（避免非数字输入异常）
            int choice = 0;
            if (scanner.hasNextInt()) {
                choice = scanner.nextInt();
                scanner.nextLine(); // 消费换行符
            } else {
                scanner.nextLine(); // 清空无效输入
                System.out.println("请输入有效的数字选项！");
                continue;
            }

            switch (choice) {
                case 1:
                    addCourse();
                    break;
                case 2:
                    addStudent();
                    break;
                case 3:
                    addScoreToStudent();
                    break;
                case 4:
                    calculateStudentGPA();
                    break;
                case 5:
                    queryStudentCourseScore();
                    break;
                case 6:
                    saveData();
                    break;
                case 7:
                    loadData();
                    break;
                case 0:
                    System.out.println("系统已退出");
                    scanner.close();
                    return;
                default:
                    System.out.println("无效选项，请重新选择");
            }
        }
    }

    // 1. 添加课程
    private static void addCourse() {
        System.out.print("请输入课程编号：");
        String courseId = scanner.nextLine();
        // 校验课程编号是否重复
        for (Course c : courses) {
            if (c.getId().equals(courseId)) {
                System.out.println("该课程编号已存在！");
                return;
            }
        }
        System.out.print("请输入课程名称：");
        String courseName = scanner.nextLine();
        System.out.print("请输入课程学分：");
        int credit = 0;
        if (scanner.hasNextInt()) {
            credit = scanner.nextInt();
            scanner.nextLine();
        } else {
            scanner.nextLine();
            System.out.println("学分必须是数字！");
            return;
        }

        courses.add(new Course(courseId, courseName, credit));
        System.out.println("课程添加成功！");
    }

    // 2. 添加学生
    private static void addStudent() {
        System.out.print("请输入学生学号：");
        String studentId = scanner.nextLine();
        // 校验学号是否重复
        for (Student s : students) {
            if (s.getId().equals(studentId)) {
                System.out.println("该学号已存在！");
                return;
            }
        }
        System.out.print("请输入学生姓名：");
        String studentName = scanner.nextLine();
        System.out.print("请输入学生班级：");
        String className = scanner.nextLine();

        students.add(new Student(studentId, studentName, className));
        System.out.println("学生添加成功！");
    }

    // 3. 为学生添加成绩
    private static void addScoreToStudent() {
        System.out.print("请输入学生学号：");
        String studentId = scanner.nextLine();
        Student targetStudent = null;
        for (Student s : students) {
            if (s.getId().equals(studentId)) {
                targetStudent = s;
                break;
            }
        }
        if (targetStudent == null) {
            System.out.println("未找到该学生！");
            return;
        }

        System.out.print("请输入课程编号：");
        String courseId = scanner.nextLine();
        Course targetCourse = null;
        for (Course c : courses) {
            if (c.getId().equals(courseId)) {
                targetCourse = c;
                break;
            }
        }
        if (targetCourse == null) {
            System.out.println("未找到该课程！");
            return;
        }

        System.out.print("请输入分数（0-100）：");
        int scoreValue = 0;
        if (scanner.hasNextInt()) {
            scoreValue = scanner.nextInt();
            scanner.nextLine();
        } else {
            scanner.nextLine();
            System.out.println("分数必须是数字！");
            return;
        }

        try {
            Score score = new Score(targetStudent, targetCourse, scoreValue);
            targetStudent.addScore(score);
            System.out.println("成绩添加成功！");
        } catch (IllegalArgumentException e) {
            System.out.println("成绩添加失败：" + e.getMessage());
        }
    }

    // 4. 计算学生GPA
    private static void calculateStudentGPA() {
        System.out.print("请输入学生学号：");
        String studentId = scanner.nextLine();
        for (Student s : students) {
            if (s.getId().equals(studentId)) {
                double gpa = s.calculateGPA();
                System.out.printf("%s的GPA为：%.2f\n", s.getName(), gpa);
                return;
            }
        }
        System.out.println("未找到该学生！");
    }

    // 5. 查询学生课程成绩
    private static void queryStudentCourseScore() {
        System.out.print("请输入学生学号：");
        String studentId = scanner.nextLine();
        Student targetStudent = null;
        for (Student s : students) {
            if (s.getId().equals(studentId)) {
                targetStudent = s;
                break;
            }
        }
        if (targetStudent == null) {
            System.out.println("未找到该学生！");
            return;
        }

        System.out.print("请输入课程编号：");
        String courseId = scanner.nextLine();
        try {
            int score = targetStudent.queryCourseScore(courseId);
            System.out.printf("%s的%s成绩为：%d\n",
                    targetStudent.getName(),
                    getCourseNameById(courseId),
                    score);
        } catch (Exception e) {
            System.out.println("查询失败：" + e.getMessage());
        }
    }

    // 辅助方法：通过课程ID获取课程名称
    private static String getCourseNameById(String courseId) {
        for (Course c : courses) {
            if (c.getId().equals(courseId)) {
                return c.getName();
            }
        }
        return "未知课程";
    }

    // 6. 保存数据到文件
    private static void saveData() {
        System.out.print("请输入保存的文件名：");
        String filename = scanner.nextLine();
        try {
            ScoreSystem.saveToFile(students, courses, filename);
        } catch (Exception e) {
            System.out.println("保存失败：" + e.getMessage());
        }
    }

    // 7. 从文件加载数据
    private static void loadData() {
        System.out.print("请输入加载的文件名：");
        String filename = scanner.nextLine();
        try {
            students.clear();
            courses.clear();
            ScoreSystem.loadFromFile(students, courses, filename);
        } catch (Exception e) {
            System.out.println("加载失败：" + e.getMessage());
        }
    }
}